from rest_framework import viewsets, mixins, status
from rest_framework import response
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.db.models import Q
from rest_framework.filters import SearchFilter

from utils.permissions import IsSuperUser
from users.filter import UserFilter, GroupFilter
from permissions.common import get_menu_tree
from users.serializers import UserSerializer, GroupSerializer
User = get_user_model()


class UserViewset(viewsets.ModelViewSet):
    """
    list: 返回用户列表
    retrieve: 返回单个用户信息
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer
    # pagination_class = PageNumberPagination  # 分页，已经设置settings中默认
    # filter_backends = (DjangoFilterBackend, )  # 写入settings中，变成默认的
    filter_backends = (SearchFilter,)
    search_fields = ('username', 'role', 'name', 'email', 'phone')
    filter_class = UserFilter  # 搜索，指定搜索类，可以导入自定义的
    filter_fields = ('username', 'groups', 'role')
    permission_classes = (IsAuthenticated, IsSuperUser)  # 管理员权限才能修改


class UserInfoViewset(viewsets.ViewSet):
    """
    前端获取用户基础信息
    """
    permission_classes = (IsAuthenticated, )

    def list(self, request, *args, **kwargs):
        name = request.user.name if request.user.name else request.user.username
        data = {
            "id": request.user.id,
            "username": request.user.username,
            "name": name,
            "menus": get_menu_tree(self.request.user.get_view_permissions()),
            "superuser": request.user.is_superuser,
            "role": request.user.role
        }
        return response.Response(data)


class GroupsViewset(viewsets.ModelViewSet):
    """
    list: 返回用户列表
    retrieve: 返回单个用户组信息
    """
    queryset = Group.objects.all().order_by('id')
    serializer_class = GroupSerializer
    # pagination_class = PageNumberPagination
    # filter_backends = (DjangoFilterBackend, )
    filter_class = GroupFilter
    filter_fields = ('name', )


class UserGroupViewset(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    获取用户的组信息
    retrieve: 返回指定用户所有组
    """

    queryset = User.objects.all().order_by('id')
    serializer_class = GroupSerializer

    def retrieve(self, request, *args, **kwargs):
        user_obj = self.get_object()
        queryset = user_obj.groups.all()

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return response.Response(serializer.data)


class GroupMembersViewset(mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
                          mixins.DestroyModelMixin, viewsets.GenericViewSet):
    """
    用户组成员管理
    retrieve: 返回指定组的成员列表
    update: 往指定组里添加成员
    destroy: 从指定组删除成员
    """

    queryset = Group.objects.all()
    serializer_class = UserSerializer

    def retrieve(self, request, *args, **kwargs):
        group_obj = self.get_object()
        queryset = group_obj.user_set.all()
        search = request.GET.get('name', None)  # 获取搜索关键字

        if search is not None:  # 有搜索关键字时对姓名和用户名进行搜索
            queryset = queryset.filter(Q(name__icontains=search) | Q(username__icontains=search))
        queryset = self.filter_queryset(queryset)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return response.Response(serializer.data)

    def update(self, request, *args, **kwargs):
        result = {'status': 0}
        group_obj = self.get_object()
        user_obj = self.get_user_obj(request.data.get('uid', 0))
        if user_obj is None:
            result['status'] = 1
            result['errmsg'] = '用户错误'
        else:
            group_obj.user_set.add(user_obj)
        return response.Response(result, status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        ret = {"status": 0}
        group_obj = self.get_object()
        user_obj = self.get_user_obj(request.data.get("uid", 0))
        if user_obj is None:
            ret["status"] = 1
            ret["errmsg"] = "用户错误"
        else:
            group_obj.user_set.remove(user_obj)
        return response.Response(ret, status=status.HTTP_200_OK)

    @staticmethod
    def get_user_obj(uid):
        try:
            return User.objects.get(pk=uid)
        except User.DoesNotExist:
            return None
